package com.genymobile.scrcpy.five.connection;

import android.text.TextUtils;

import com.genymobile.scrcpy.five.GlobalConfig;
import com.genymobile.scrcpy.five.LogUtils;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

public class ConnectionClient {
    private OutputStream outputStream;
    private Socket mSocket;
    private final int mPort;
    ConnectionClient(int port) {
        mPort = port;
        connect();
    }

    private boolean checkSocketValid() {
        if (mSocket != null) {
            try {
                mSocket.sendUrgentData(0xFF); // 发送1字节紧急数据
            } catch (IOException e) {
                mSocket = null;
                outputStream = null;
                return false;
            }
        }
        return true;
    }

    private synchronized void connect() {
        final String ip = "127.0.0.1";
        try {
            if (mSocket != null) {
                try {
                    mSocket.close();
                } catch (IOException ignored) {}
            }
            mSocket = new Socket(ip, mPort);
            outputStream = mSocket.getOutputStream();
        } catch (IOException ignored) {
        }
    }

    public synchronized void send(String line) {
        if (TextUtils.isEmpty(line)) {
            return;
        }
        if (GlobalConfig.LOG_ENABLE)    LogUtils.log("send()", line);
        if (outputStream == null) {
            connect();
        } else {
            if (!checkSocketValid()) {
                send(line);
                return;
            }
        }
        if (outputStream != null) {
            try {
                outputStream.write(line.getBytes());
                outputStream.flush();
            } catch (IOException e) {
                outputStream = null;
                send(line);
            }
            return;
        }
        if (GlobalConfig.LOG_ENABLE)    LogUtils.loge("connection client:", "can't send: " + line);
    }
}
